<template>
  <div>
    <FormPanel ref="formPanel" :list="formList" :formType="type" @formChange="changeHandle" :isSubmitBtn="false" :collapse="false" labelWidth="110" />
    <BreakSpace label="操作记录" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable ref="table" :isSelectColumn="false" :columns="columns" :dataSource="tableLists" :onColumnsChange="columns => (this.columns = columns)"> </FilterTable>

    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'center'
      }"
    >
      <el-button @click="closeDrawer">关 闭</el-button>
    </div>
    <BaseDialog :visible.sync="isRule" title="对应折扣规则" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <SelectRule :rowData="formData" @close="emitCloseHandler" />
    </BaseDialog>

    <BaseDialog :visible.sync="isDealer" title="经销商清单" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <SelectDealer :rowData="formData" @close="emitCloseHandler1" />
    </BaseDialog>

    <BaseDialog :visible.sync="isModel" title="选装清单" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <SelectModel :rowData="formData" @close="emitCloseHandler2" />
    </BaseDialog>
  </div>
</template>
<script>
import moment from 'moment';
import { dictionary } from '@/utils/dictMixin';
import { queryOrderTypeSub, getFiAccountType, getFiDiscountPolicyById, auditFiDiscountPolicy } from '@/api/omFinance/PriceDiscountManage/DiscountStrategyReview';
import { getflowList } from '@/api/index.js';

import SelectRule from './SelectRule';
import SelectDealer from './SelectDealer';
import SelectModel from './SelectModel';
import { getDealerUser } from '@/api/omFinance';

export default {
  name: 'SonModel',
  mixins: [dictionary],
  components: {
    SelectRule,
    SelectDealer,
    SelectModel
  },
  props: {
    type: {
      type: String,
      default: 'show'
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    this.saveData = null;
    this.ruleList = null;
    this.dealerList = null;
    this.optionList = null;
    return {
      formList: this.createdFrom(),
      columns: this.createdTable(),
      fetchParams: {},
      fetchApi: () => {},
      formData: {},
      isRule: false,
      isModel: false,
      isDealer: false,

      tableLists: []
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      if (this.type == 'edit') {
        this.payWay();
        this.orderTypeSub();
        this.getInfoById();
        // this.getUser();
        this.getflowList();
      }
    },
    async getUser() {
      let res = await getDealerUser();
      let empList = res.data.map(x => ({ text: x.userName, value: x.userId }));
      this.columns.find(item => item.dataIndex === 'updated_by').editItems = empList; //操作姓名
      this.columns.find(item => item.dataIndex === 'updated_by').filterItems = empList;
    },
    // 详细
    async getInfoById() {
      const res = await getFiDiscountPolicyById(this.rowData.id);
      if (res.resultCode == 200) {
        this.formList.forEach(x => {
          if (x.fieldName == 'rule') {
            this.ruleList = res.data.ruleList;
          } else if (x.fieldName == 'dealer') {
            this.dealerList = res.data.dealerDTOList;
          } else if (x.fieldName == 'option') {
            this.optionList = res.data.optionList;
          } else if (x.fieldName == 'fiPolicySettlement') {
            // 结算方式
            x.initialValue = res.data.fiPolicySettlementDTOList.map(y => y.settlement);
          } else if (x.fieldName == 'delivery') {
            // 提货方式
            x.initialValue = [];
            res.data.deliveryDTOList.map(y => {
              x.initialValue.push(y.deliveryType);
            });
          } else if (x.fieldName == 'fileUrl') {
            // 上传附件 由数组改为字符串
            if (res.data['fileUrl']) {
              let tempArr = [];
              let tempArr1 = [];
              let tempArr2 = [];

              let fileUrl = [];

              tempArr = res.data['fileUid'].split(',');
              tempArr1 = res.data['fileUrl'].split(',');
              tempArr2 = res.data['fileName'].split(',');
              tempArr.map((x, key) => {
                let json = {
                  uid: x,
                  url: tempArr1[key],
                  name: tempArr2[key]
                };
                fileUrl.push(json);
              });
              x.initialValue = fileUrl;
              console.log(fileUrl, '---奥利给---');
              return;
            }
            x.initialValue = [];
          } else {
            x.initialValue = res.data[x.fieldName];
          }
        });
      }
    },
    async getflowList() {
      let res = await getflowList({ module: 'cms_retail', tableName: 'tm_fi_discount_policy', pk: this.rowData.id, order: 'desc' });
      if (res.data && res.data.length > 0) {
        res.data.map(x => {
          let data = JSON.parse(x.data);
          x.updated_by = Number(data.updated_by);
          x.updated_at = data.updated_at;
          x.business_status = data.check_status;
          x.check_ramark = data.check_ramark;
          x.audit_remark = data.audit_remark;
        });
      }
      console.log(res.data, '1');
      this.tableLists = res.data || [];
    },
    // 订单细分查询接口
    async orderTypeSub(orderType) {
      let params = { orderType: orderType, isAvailable: 10041001 };
      const res = await queryOrderTypeSub(params);
      if (res.resultCode == 200) {
        this.formList.find(item => item.fieldName == 'orderTypeSub').itemList = res.data.map(x => ({ text: x.subName, value: x.subId }));
      }
    },
    changeHandle(val) {
      this.saveData = val;
    },
    ruleHandle() {
      console.log('---折扣规则---');
      this.isRule = true;
      this.formData = this.ruleList;
    },
    dealerHandle() {
      console.log('---经销商---');
      this.isDealer = true;
      this.formData = this.dealerList;
    },
    modelHandle() {
      console.log('---车型---');
      this.isModel = true;
      this.formData = this.optionList;
    },

    emitCloseHandler(val) {
      this.isRule = val;
    },
    emitCloseHandler1(val) {
      this.isDealer = val;
    },
    emitCloseHandler2(val) {
      this.isModel = val;
    },
    // 驳回
    async rejectHandle() {
      this.formList.find(x => x.fieldName == 'auditRemark').rules[0].required = true;

      this.$refs.formPanel.SUBMIT_FORM();

      if (this.saveData !== null) {
        this.saveData.ruleList = this.ruleList;
        this.saveData.dealerDTOList = this.dealerList;
        this.saveData.optionList = this.optionList;
        let tempArr = [];
        let tempArr1 = [];
        if (this.saveData.delivery.length > 0) {
          this.saveData.delivery.map(x => {
            let json = {
              deliveryType: x.deliveryType ? x.deliveryType : x
            };
            tempArr.push(json);
          });
        }
        if (this.saveData.fiPolicySettlement.length > 0) {
          this.saveData.fiPolicySettlement.map(x => {
            let json = {
              settlement: x.settlement ? x.settlement : x
            };
            tempArr1.push(json);
          });
        }
        this.saveData.deliveryDTOList = JSON.parse(JSON.stringify(tempArr));
        this.saveData.fiPolicySettlementDTOList = JSON.parse(JSON.stringify(tempArr1));
        this.saveData.checkStatus = 60291004;

        let saveData = Object.assign({}, this.rowData, this.saveData);
        console.log(saveData, '---提报的数据---');
        const res = await auditFiDiscountPolicy(saveData);
        if (res.resultCode === 200) {
          await this.closeDrawer('refresh');
        }
      }
    },
    // 结算方式 getFiAccountType
    async payWay() {
      let param = {
        fundsType: 0
      };
      const res = await getFiAccountType(param);
      if (res.resultCode === 200) {
        this.formList.find(item => item.fieldName == 'fiPolicySettlement').itemList = res.data.map(x => ({ text: x.accountTypeName, value: x.id }));
      }
    },
    // 通过
    async submitHandle() {
      this.formList.find(x => x.fieldName == 'auditRemark').rules[0].required = false;
      this.$refs.formPanel.SUBMIT_FORM();
      if (this.saveData !== null) {
        this.saveData.ruleList = this.ruleList;
        this.saveData.dealerDTOList = this.dealerList;
        this.saveData.optionList = this.optionList;
        let tempArr = [];
        let tempArr1 = [];
        if (this.saveData.delivery && this.saveData.delivery.length > 0) {
          this.saveData.delivery.map(x => {
            let json = {
              deliveryType: x.deliveryType ? x.deliveryType : x
            };
            tempArr.push(json);
          });
        }
        if (this.saveData.fiPolicySettlement && this.saveData.fiPolicySettlement.length > 0) {
          this.saveData.fiPolicySettlement.map(x => {
            let json = {
              settlement: x.settlement ? x.settlement : x
            };
            tempArr1.push(json);
          });
        }
        this.saveData.deliveryDTOList = tempArr;
        this.saveData.fiPolicySettlementDTOList = tempArr1;
        this.saveData.checkStatus = 60291003;
        let saveData = Object.assign({}, this.rowData, this.saveData);
        console.log(saveData, '---提报的数据---');
        const res = await auditFiDiscountPolicy(saveData);
        if (res.resultCode === 200) {
          await this.closeDrawer('refresh');
        }
      }
    },
    closeDrawer(type) {
      this.$emit('close', false, type);
    },
    selectChangeHandle() {},

    createdFrom() {
      return [
        {
          type: 'INPUT',
          label: '折扣策略名称',
          fieldName: 'policyName',
          placeholder: '',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '折扣规则',
          fieldName: 'rule',
          placeholder: '点击图标查看',
          readonly: true,
          unitRender: () => {
            return (
              <div>
                <el-button icon="el-icon-document" onClick={() => this.ruleHandle()}></el-button>
              </div>
            );
          }
        },
        {
          type: 'SELECT',
          label: '动力形式',
          fieldName: 'powerType',
          placeholder: '',
          disabled: true,
          itemList: this.createDictList('6008')
        },
        {
          type: 'INPUT',
          label: '适用经销商',
          fieldName: 'dealer',
          placeholder: '点击图标查看',
          readonly: true,
          unitRender: () => {
            return (
              <div>
                <el-button icon="el-icon-document" onClick={() => this.dealerHandle()}></el-button>
              </div>
            );
          }
        },
        {
          type: 'INPUT',
          label: '适用车型',
          fieldName: 'option',
          placeholder: '点击图标查看',
          readonly: true,
          unitRender: () => {
            return (
              <div>
                <el-button icon="el-icon-document" onClick={() => this.modelHandle()}></el-button>
              </div>
            );
          }
        },
        {
          type: 'MULTIPLE_SELECT',
          label: '结算方式',
          fieldName: 'fiPolicySettlement',
          placeholder: '',
          disabled: true,
          hidden: true,
          itemList: []
        },
        {
          type: 'MULTIPLE_SELECT',
          label: '提货方式',
          fieldName: 'delivery',
          placeholder: '',
          disabled: true,
          itemList: this.createDictList('6004'),
          initialValue: [60041001, 60041002]
        },
        {
          type: 'SELECT',
          label: '启用标记',
          fieldName: 'status',
          placeholder: '',
          initialValue: 10031001,
          disabled: true,
          itemList: this.createDictList('1003')
        },
        {
          type: 'SELECT',
          label: '适用订单类型',
          fieldName: 'orderType',
          placeholder: '',
          itemList: this.createDictList('6006'),
          disabled: true
        },
        {
          type: 'SELECT',
          label: '适用订单细分',
          fieldName: 'orderTypeSub',
          placeholder: '',
          itemList: [],
          disabled: true
        },
        {
          type: 'SELECT',
          label: '经销商级别',
          fieldName: 'dealerLevel',
          placeholder: '',
          disabled: true,
          itemList: this.createDictList('2542')
        },
        {
          type: 'DATE',
          label: '生效日期',
          fieldName: 'startDate',
          dateType: 'exactdate',
          placeholder: '',
          disabled: true,
          minDateTime: moment().add(-1, 'days')
        },
        {
          type: 'DATE',
          label: '失效日期',
          fieldName: 'endDate',
          dateType: 'exactdate',
          placeholder: '',
          disabled: true,
          minDateTime: moment().add(-1, 'days')
        },
        {
          type: 'UPLOAD_FILE',
          label: '上传附件',
          fieldName: 'fileUrl',
          upload: {
            actionUrl: '/api/file/oss/upload',
            fileTypes: ['jpg', 'png', 'pdf'],
            limit: 999
            // tipText: '最多上传1个附件'
          }
        }
        // {
        //   type: 'TEXT_AREA',
        //   label: '审核意见',
        //   fieldName: 'auditRemark',
        //   placeholder: '',
        //   initialValue: '',
        //   selfCols: 3,
        //   maxlength: 200,
        //   disabled: true
        // }
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作状态',
          dataIndex: 'business_status',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('6029'),
          render: p => {
            return <span>{this.createDictText(p.row.business_status, '6029')}</span>;
          }
        },
        {
          title: '操作人员',
          dataIndex: 'updatedByName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '操作时间',
          dataIndex: 'updated_at',
          sorter: true,
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '审核备注',
          dataIndex: 'audit_remark',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    }
  }
};
</script>
